package org.easymodelers.gmf.update;

import java.util.Map;

import org.easymodelers.expression.ExpressionData;
import org.easymodelers.expression.ExpressionParser;
import org.easymodelers.gmf.GmfGenUpdate;
import org.easymodelers.template.utils.DynamicModelManager;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.gmf.codegen.gmfgen.GenEditorGenerator;

public class ExpressionBasedGenUpdate extends AbstractGenModelUpdate implements GmfGenUpdate {
	private Map<String,Object> expressions;
	
	public ExpressionBasedGenUpdate() {
	}

	public ExpressionBasedGenUpdate(Map<String,Object> expressions) {
		this.expressions = expressions;
	}

	protected boolean isValueForFieldNotEmpty(String value) {
		return (value!=null && !value.trim().equals(""));
	}
	
	public void updateGenModel(GenEditorGenerator rootEObject) {
		if (expressions==null) {
			return;
		}

		for (String expression  : expressions.keySet()) {
			ExpressionParser expressionParser = new ExpressionParser(expression);
			ExpressionData expressionData = expressionParser.parse();

			Object value = expressions.get(expression);
			
			EList<EObject> eobjects = getEObjectsForExpression(rootEObject, expressionData);
			for (EObject eObject : eobjects) {
				DynamicModelManager.setAttribute(eObject, expressionData.getFieldName(), value);
			}
		}
	}

	public Map<String, Object> getExpressions() {
		return expressions;
	}

	public void setExpressions(Map<String, Object> expressions) {
		this.expressions = expressions;
	}

}
